import librosa
import io
import numpy as np
import PyWave

def GetWaveInfo(wavPath):  
    wf = PyWave.open(wavPath)
    print(f"This WAVE file [{wavPath}] has the following properties:")
    print(wf.channels, "channels")
    print(wf.frequency, "Hz sample rate")
    print(wf.bitrate, "bits per second")
    print(wf.samples, "total samples")
    print(wf.data_length, "data bytes")
    duration = (float)(wf.samples) / wf.frequency   # 音频持续时间 单位：秒
    print(f'duration : {duration}')
    return wf.frequency

def load_and_preprocess_audio(audio_path):
    sr = GetWaveInfo(audio_path)
    y, sr = load_audio(audio_path)
    if sr != 88200:
        y = librosa.resample(y, orig_sr=sr, target_sr=88200)
        sr = 88200

    max_val = np.max(np.abs(y))
    if max_val > 0:
        y = y / max_val

    return y, sr

def load_audio(audio_path):
    y, sr = librosa.load(audio_path)
    print(f"Loaded audio file '{audio_path}' with sample rate {sr}")
    return y, sr

def load_audio_from_bytes(audio_bytes):
    audio_file = io.BytesIO(audio_bytes)
    y, sr = librosa.load(audio_file)
    
    max_val = np.max(np.abs(y))
    if max_val > 0:
        y = y / max_val


    return y, sr

def load_audio_file_from_memory(audio_bytes):
    """Load audio from memory bytes."""
    y, sr = librosa.load(io.BytesIO(audio_bytes))
    print(f"Loaded audio data with sample rate {sr}")
    
    max_val = np.max(np.abs(y))
    if max_val > 0:
        y = y / max_val


    return y, sr